package world.hezi.http;

import net.mamoe.mirai.event.events.MessageEvent;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import world.hezi.utils.CommonUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SendChatGPT {
    final private static Map<String,String> HEADERS_MAP = new HashMap<>();
    static String url = "https://chat.openai.com/backend-api/conversation";
    private static final Pattern PATTERN = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
    static {
        HEADERS_MAP.put("authority","chat.openai.com");
        HEADERS_MAP.put("accept","text/event-stream");
        HEADERS_MAP.put("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        HEADERS_MAP.put("Content-Type","application/json");
        HEADERS_MAP.put("cookie","_ga=GA1.2.412361248.1670564816; intercom-session-dgkjq2bp=M2VyekRJWG14NXAzaGpwbGMyWDFyTXhpNTN6Y3B3VGRZb0w1ZmgwVC8wTFFRYnlpMXA5VWd3UFVzWVRtTHlzRi0tRVh5S0VZb1VpYVB0b210K1VpbmhoUT09--5fe1f3aedd215cfabf7fedb87c6bb240dd5e0bef; intercom-device-id-dgkjq2bp=90bc3da8-73e7-4b00-9c23-9f4000fac3a3; cf_clearance=Hxk3zBnivvjQUgUEzf5uHn2DleU6.SI0OM5D5jIQZZg-1670812015-0-160; __Host-next-auth.csrf-token=ddf4f52c78fb842e7061581f0cf1532a4094413cc36df41a584a37ab121a7b42|ad56e04929e51960773a6b15a794e60d9e9a3bd4082e3d391115a7328321ae09; __Secure-next-auth.callback-url=https://chat.openai.com/; __cf_bm=iDhaqAdmFnMdjDMxCCwHLZzqrnZoeC8yhi_HchAzh7Y-1670814577-0-ARV+cDJT4zaYwx/HJcyzMDk7yzFe+lN0uausAzWkmTTnnjfC8k3s0mf0JFv2hGft0/Tym237RQgQXrFryGYQHVhnsEJbKeJ9KXmf/JTy7QxjJ9wrT/vF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Hd5FN3wGf07aGH1ADyYDxaFIh4Fn3h_VEMQEndrK2Y4yw_go-0HW3l1y3WXh0I3n5s2qmfyU7UH8pYbiYyq3Lu9R12s_Unw1qtXICVJJrl-0KCQu8s83QdVvm79Pk1ExZLdkUIyhazlPYNuLFS53LAt7-_1iecSfTULKbAXb7-avnIxjcB35UigbsDx9JonyD-mbgRUV7JHUvY5TFtU4peJy_EJCoejWE24FrrZwgzB5UIKpf4gSzpBxiYy7W0ICyCJz4pZIFOMObfRj8qlP5P7IAwpdzTqVuDv8Q66tFJxuOXp9aD8HTQc2PEYv7vsTUufuovwJCJTf0acLZc6hLb9sZdQ.mxzWMqnmu3hwSOq0dDitTw");
        HEADERS_MAP.put("origin","https://chat.openai.com");
        HEADERS_MAP.put("referer","https://chat.openai.com/chat");
        HEADERS_MAP.put("sec-ch-ua","\"Not?A_Brand\";v=\"8\", \"Chromium\";v=\"108\", \"Microsoft Edge\";v=\"108\"");
        HEADERS_MAP.put("sec-ch-ua-platform","\"Windows\"");
        HEADERS_MAP.put("sec-fetch-mode","cors");
        HEADERS_MAP.put("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.42");
        HEADERS_MAP.put("authorization","Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Ik1UaEVOVUpHTkVNMVFURTRNMEZCTWpkQ05UZzVNRFUxUlRVd1FVSkRNRU13UmtGRVFrRXpSZyJ9.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL3Byb2ZpbGUiOnsiZW1haWwiOiJ5YXdlenhAbWFpbHRvLnBsdXMiLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiZ2VvaXBfY291bnRyeSI6IlVTIn0sImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJ1c2VyX2lkIjoidXNlci10Z0J5dzk1VWhybmdvRTBlSWQ0c1dyQ2kifSwiaXNzIjoiaHR0cHM6Ly9hdXRoMC5vcGVuYWkuY29tLyIsInN1YiI6ImF1dGgwfDYzOTJlNGYyYzMzYmE0ZjIyMDdiZGRkMiIsImF1ZCI6WyJodHRwczovL2FwaS5vcGVuYWkuY29tL3YxIiwiaHR0cHM6Ly9vcGVuYWkuYXV0aDAuY29tL3VzZXJpbmZvIl0sImlhdCI6MTY3MDgxMjAyNiwiZXhwIjoxNjcwODU1MjI2LCJhenAiOiJUZEpJY2JlMTZXb1RIdE45NW55eXdoNUU0eU9vNkl0RyIsInNjb3BlIjoib3BlbmlkIGVtYWlsIHByb2ZpbGUgbW9kZWwucmVhZCBtb2RlbC5yZXF1ZXN0IG9yZ2FuaXphdGlvbi5yZWFkIG9mZmxpbmVfYWNjZXNzIn0.COg8_tGz9HFFEXZooNrpzqqnO6uCVOT5ZI6lRNnJkDR_fSvyjytyPrScsTp8XXWUjTFAcMlYbOl8qApMEmFmgulUdxzfMYGicFTRry6hOxl6mdAzJq4dawMo7JrjUhRw3_labdwWtVOphKjaiwV7gbSgy91TSzkMaFKrTJw5rRUhN9gwnHVEaCjUNHT7RWfqoDdOStGOa2Bcq33Mwc3mFtFCx5RKb6yslpX-1Jn_2cIKWOy6DWPoyyaGEkDXbxZcCp-1UZm8mS8zkqV3aF-TIvxRz8pOfdeGqjSJ43K_dBtuBDQn35nuFwZ5tXP86HeS0wIW_hXpf_n_bI8pu-wiLQ");
    }
    private static String LAST = UUID.randomUUID().toString();
    public static void execute(MessageEvent event, String message){
        message = message.replaceAll("\n","");
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        MediaType JsonType = MediaType.parse("application/json; charset=utf-8");
        String lastId = LAST;
        LAST = UUID.randomUUID().toString();
        String c = "{\n" +
                "  \"action\": \"next\",\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"id\": \""+lastId+"\",\n" +
                "      \"role\": \"user\",\n" +
                "      \"content\": {\n" +
                "        \"content_type\": \"text\",\n" +
                "        \"parts\": [\n" +
                "          \""+message+"\"\n" +
                "        ]\n" +
                "      }\n" +
                "    }\n" +
                "  ],\n" +
                "  \"parent_message_id\": \""+LAST+"\",\n" +
                "  \"model\": \"text-davinci-002-render\"\n" +
                "}";
        RequestBody body = RequestBody.create(c,JsonType);
        Headers headers = Headers.of(HEADERS_MAP);
        final Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                event.getSubject().sendMessage(e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                boolean success = response.code() == 200;
                if (!success){
                    CommonUtil.sendQuoteReplyMessage(event,"HTTP ERROR\ncode = "+response.code()+"\n"+response.message());
                    return;
                }
                try {

                    CommonUtil.sendQuoteReplyMessage(event,getMsg(response.body().string()));
                }catch (Exception e){
                    if (response.body()!=null){
                        CommonUtil.sendQuoteReplyMessage(event,"可能是被限流了\n"+Objects.requireNonNull(response.body()).string()+"\n"+ CommonUtil.getException(e));
                    }else {
                        CommonUtil.sendQuoteReplyMessage(event,"可能是被限流了\n"+CommonUtil.getException(e));
                    }
                }

            }
        });
    }
    private static String getMsg(String data){
        String[] split = data.split("\n\n");
        String real = split[split.length-2];
        real = unicodeDecode(real.substring(real.indexOf("[\"")+2,real.lastIndexOf("\"]}")));
        return real.replaceAll("\\\\n","\n").replaceAll("\\\\","");

    }

    public static String unicodeDecode(String string) {

        Matcher matcher = PATTERN.matcher(string);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }
        return string;
    }

    public static void main(String[] args) {
        String test = "ns\\nf\\gg";
        System.out.println(test);
        System.out.println(Arrays.toString(test.split("\\\\")));
    }
}
